import React, { useState, useEffect, useRef } from "react";
import { Button, Form, Input, Card, message, Spin, Switch, Select } from "antd";
import { useHistory } from "react-router-dom";
import Editor from "for-editor";
import api from "@/api/blog/blog";
import moment from "moment";
import { getDict } from "@/utils/localStorage";
// import { HashRouter as Router, Route } from 'react-router-dom'
// import CacheRoute, { CacheSwitch } from 'react-router-cache-route'
// import CacheRoute, { dropByCacheKey, getCachingKeys } from 'react-router-cache-route'
const { TextArea } = Input;
// import CacheRoute, { dropByCacheKey, getCachingKeys } from 'react-router-cache-route'
export default function Index(props) {
    const [mdContent, setMdContent] = useState("");
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [top, setTop] = useState(false);
    const [topkey, setTopkey] = useState(1);
    const editorEL = useRef(null);
    const history = useHistory();
    const handleEditorChange = (value) => {
        setMdContent(value);
    };

    useEffect(() => {
        if (props.match.params.id !== "-1") getModel();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    //置顶
    const changeTop = (e) => {
        setTop(e);
    };
    //上传图片
    const addImg = ($file) => {
        editorEL.current.$img2Url($file.name, "file_url");
    };
    //获取
    const getModel = async () => {
        setLoading(true);
        const res = await api.getmodel({
            _id: props.match.params.id ? props.match.params.id : null,
        });
        setLoading(false);
        setMdContent(res.data.mdContent);
        setTop(res.data.top);
        setTopkey(2);
        form.setFieldsValue({
            type: res.data.type,
            title: res.data.title,
            coverUrl: res.data.coverUrl,
            tag: res.data.tag,
            desc: res.data.desc,
        });
    };
    //保存
    const save = async () => {
        form.validateFields().then(async () => {
            if (mdContent === "") {
                message.warning(" 提交博客不能为空 ");
                return;
            }
            let data = Object.assign({ mdContent, createTime: moment().format("YYYY-MM-DD hh:mm:ss"), top }, form.getFieldsValue(true));
            let res = null;
            if (props.match.params.id !== "-1") res = await api.update(Object.assign({ _id: props.match.params.id, top, mdContent }, form.getFieldsValue(true)));
            else res = await api.addList(data);
            message.success(res.msg);

            // console.log(getCachingKeys()) 

            goBack();
        });
    };
    //返回
    const goBack = async () => {
        history.push("/blog/blog");
    };
    const toolbar = {
        h1: true, // h1
        h2: true, // h2
        h3: true, // h3
        h4: true, // h4
        img: true, // 图片
        link: true, // 链接
        code: true, // 代码块
        preview: true, // 预览
        expand: true, // 全屏
        /* v0.0.9 */
        undo: true, // 撤销
        redo: true, // 重做
        save: true, // 保存
        /* v0.2.3 */
        subfield: true, // 单双栏模式
    };
    return (
        <>
            {loading ? (
                <Spin style={{ width: "100%", height: "100%", padding: 100 }}></Spin>
            ) : (
                <div
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                        height: "100%",
                        maxHeight: "calc(100vh - 180px)",
                    }}>
                    <Editor
                        ref={editorEL}
                        preview={props.match.params.type === "preview"}
                        value={mdContent}
                        toolbar={props.match.params.type === "preview" ? {} : toolbar}
                        style={{ width: "calc(100% - 300px)", height: "100% " }}
                        addImg={($file) => addImg($file)}
                        onChange={(e) => {
                            handleEditorChange(e);
                        }}
                    />
                    <Card
                        title=" 博客信息 "
                        extra={
                            <div>
                                置顶：
                                <Switch key={topkey} defaultChecked={top} onChange={changeTop} disabled={props.match.params.type === "preview"} />
                            </div>
                        }
                        style={{ width: 300, marginLeft: 10, paddingLeft: 0, overflowY: "scroll" }}
                        actions={[
                            <div style={{ display: "flex", justifyContent: "center" }}>
                                <Button style={{ marginRight: 20 }} type="primary" disabled={props.match.params.type === "preview"} onClick={save}>
                                    提交博客
                                </Button>
                                <Button onClick={goBack}>返回列表</Button>
                            </div>,
                        ]}>
                        <Form form={form} disabled={props.match.params.type === "preview"} name="basic" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} autoComplete="off" className="mdEdit">
                            <Form.Item label="标题：" name="title" disabled={true} rules={[{ required: true, message: "请输入文章标题!" }]}>
                                <Input placeholder="请输入文章标题" />
                            </Form.Item>

                            <Form.Item label="分类" name="type" rules={[{ required: true, message: "请输入文章类型!" }]}>
                                <Select placeholder="请输入文章标签" options={getDict("blog_type")}></Select>
                            </Form.Item>

                            <Form.Item label="标签" name="tag" rules={[{ required: true, message: "请输入文章标签!" }]}>
                                <Select placeholder="请输入文章标签" mode="multiple" options={getDict("blog_tag")}></Select>
                            </Form.Item>

                            <Form.Item label="封面：" name="coverUrl" rules={[{ required: false, message: "请输入图片链接!" }]}>
                                <Input placeholder="请输入图片链接" />
                            </Form.Item>

                            <Form.Item label="简述：" name="desc" rules={[{ required: false, message: "请输入文章简述  !" }]} className="desc">
                                <TextArea rows={4} placeholder="请输入文章简述" />
                            </Form.Item>
                        </Form>
                    </Card>
                </div>
            )}
        </>
    );
}
